package Security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * This is the passwordhash class.
 * This Class has only one method. See the method for description
 */

public class PasswordHash
{
	/**
	 * Method for password hashing. 
	 * Because WindowBuilder returns the value of password fields as a char[], this method is altered from 
	 * receiving a String to char[], and then converts the array to a string with Stringbuilder.
	 * From there the hasher "digests" each letter in password and creates it in hex format.
	 *
	 *@param password
	 * The array of characters to hash.
	 *
	 *@returns 
	 * The hashed value of the password as a String. 
	 */
    public static String HashPassword(char[] password)
    {
        String generatedPassword = "";
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            StringBuilder sb1 = new StringBuilder();
            for(int i=0; i< password.length ;i++)
            {
                sb1.append(password[i]);
            }
            String value = sb1.toString();
            md.update(value.getBytes());
            value = ""; // clear variables holding real pw
            sb1.delete(0, sb1.length()); // and here
            //Get the hash's bytes
            byte[] bytes = md.digest();
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb2 = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb2.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb2.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        return generatedPassword;
    }
}